package com.h3c.gm.common.filter

import io.jsonwebtoken.Claims
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.SignatureException
import org.springframework.util.StringUtils

import javax.servlet.Filter
import javax.servlet.FilterChain
import javax.servlet.FilterConfig
import javax.servlet.ServletException
import javax.servlet.ServletRequest
import javax.servlet.ServletResponse
import javax.servlet.http.HttpServletRequest

/**
 * Created by d14287 on 2017/6/27.
 */
class AuthFilter implements Filter {
    String excludedUrl = '/auth/login'

    @Override
    void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) servletRequest

        if (excludedUrl.equals(request.getRequestURI())) {
            filterChain.doFilter(servletRequest, servletResponse)
            return
        }
        String token = null
        if ('GET'.equals(request.getMethod())) {
            token = request.getParameter('token')
            if (StringUtils.isEmpty(token)) {
                //throw new ServletException('Invalid token')
                //目前当做正常处理
                filterChain.doFilter(servletRequest, servletResponse)
                return
            }
        }
        try {
            final Claims claims = Jwts.parser().setSigningKey('secretkey')
                    .parseClaimsJws(token).getBody()
            request.setAttribute('claims', claims)
        }
        catch (final SignatureException e) {
            throw new ServletException('Invalid token.')
        }
        filterChain.doFilter(servletRequest, servletResponse)
    }

    @Override
    void destroy() {

    }
}
